package cn.wolfcode.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;

/**
 * @ClassName CglibTest
 * @Description TODO
 * @Author xdzhango
 * @Date 2020/5/19 16:24
 **/
public class CglibTest {
    public static void main(String[] args) {
        //创建目标对象
        final CglibService cglibService = new CglibService();
        //创建代理对象
        Enhancer enhancer = new Enhancer();
        //设置增强类加载器
        enhancer.setClassLoader(cglibService.getClass().getClassLoader());
        //设置代理对象父类类型
        enhancer.setSuperclass(cglibService.getClass());
        //设置回调函数
        enhancer.setCallback(new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("做某些事前的准备");
                Object object = method.invoke(cglibService,objects);
                System.out.println("做某些事后期收尾");
                return object;
            }
        });
        //创建代理对象
        CglibService proxy = (CglibService) enhancer.create();
        //执行代理对象业务
        proxy.save("灵儿妹妹喜欢逍遥哥哥"+"----");
    }
}
